<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { 
  getCurrentInstance,
  showToast,
  showLoading,
  hideLoading,
  requestPayment
} from '@tarojs/taro';
import { request } from '@/service/request';
import { useImage } from '@/hooks';
import { useAuthStore } from '@/store';
import { storeToRefs } from 'pinia';
import { IconFont } from '@nutui/icons-vue-taro';
const { nurseUser } = storeToRefs(useAuthStore());



interface VideoDetail {
  id: string;
  name: string;
  createTime: string;
  vedio: string;
  price: number;
  cover?: string;
  detail?: string;
}

const { router } = getCurrentInstance() as any;
const { id = '' } = router?.params || {};

const video = ref<VideoDetail>({
    id: '1',
    name: '美丽的自然风光',
    createTime: '2023-11-05T10:30:00',
    vedio: 'https://anfine.huasun-healthcare.com/api/sys/common/static/temp/378506866240749575_1751388944679.mp4',
    price: 9.9,
    detail: '一段展示壮丽山脉、清澈湖泊和茂密森林的自然风光视频，带您领略大自然的神奇魅力。'
});

const loading = ref(false);
const hasPurchased = ref(false);

definePageConfig({
  navigationBarTitleText: '视频详情'
});

// 获取视频详情
const fetchVideoDetail = async () => {
  if (!id) return;
  try {
    showLoading({ title: '加载中' });
    const { error, success } = await request.get<VideoDetail>(`/vedio_shop/vedioShop/queryById?id=${id}`, {}, {
      useErrMsg: true
    });
    if (!error && success) {
      video.value = success;
      if(video.value.price == 0){
        hasPurchased.value = true;
      }
      else{
        checkBuy();
        // hasPurchased.value = true;
      }
    } else {
      showToast({ title: error?.message || '获取失败', icon: 'error' });
    }
  } catch (err) {
    // 视频详情获取失败
    showToast({ title: '获取失败', icon: 'error' });
  } finally {
    hideLoading();
  }
};

const checkBuy = async () => {
  //news_order/newsOrder/listByWeChat?userId=${nurseUser.value.id}&newsId=${id}&status=2
  const { error, success } = await request.get<any>(`/vedio_order/vedioOrder/listByWeChat`, {
    userId: nurseUser.value.id,
    vedioId: id,
    status: 2
  }, {
    useErrMsg: true
  });
  // res success
  if(error){
    hasPurchased.value = false
  }else{
    hasPurchased.value = success?.length > 0
  }
}

// 购买视频
const buyVideo = async () => {
  if (loading.value || hasPurchased.value) return;
  loading.value = true;
  try {
    showLoading({ title: '下单中' });
    const { error, success } = await request.post<any>('/vedio_order/vedioOrder/addByWeChat', {
      vedioId: video.value.id,
      userId: nurseUser.value.id,
    }, {
      useErrMsg: true
    });
    // res buy
    if (error || !success) {
      showToast({ title: error?.message || '下单失败', icon: 'error' });
      return;
    }
    // const { timeStamp, nonceStr, package: packAge, paySign, signType = 'RSA' } = success;
    const { timestamp, noncestr, package: packAge, sign } = success;


    await requestPayment({
        timeStamp: timestamp,
        nonceStr: noncestr,
        package: packAge,
        paySign: sign,
        signType: 'RSA',
      success: () => {
        showToast({ title: '支付成功', icon: 'success' });
        hasPurchased.value = true;
      },
      fail: () => {
        showToast({ title: '支付失败', icon: 'error' });
      }
    });
  } catch (err) {
    // 下单失败
    showToast({ title: '下单失败', icon: 'error' });
  } finally {
    hideLoading();
    loading.value = false;
  }
};

onMounted(() => {
  fetchVideoDetail();
  // checkBuy()
});
</script>

<template>
  <view class="min-h-screen bg-gray-50 pb-[200rpx] relative">
    <!-- 全局遮罩层 -->
    <view 
      v-if="!hasPurchased"
      class="fixed inset-0 bg-black bg-opacity-20 z-10 pointer-events-none"
    ></view>
    
    <!-- 头部信息 -->
    <view class="bg-white p-[32rpx] mb-[20rpx] relative">
      <view class="flex items-center justify-between mb-[16rpx]">
        <view class="flex-1">
          <view class="text-[40rpx] font-bold text-gray-800 mb-[16rpx] leading-tight">{{ video.name }}</view>
          <view class="text-[24rpx] text-gray-500 flex items-center">{{ video.createTime }}</view>
        </view>
        <!-- 未购买时的锁定标识 -->
        <view 
          v-if="!hasPurchased"
          class="flex items-center px-[16rpx] py-[8rpx] bg-red-50 rounded-full border border-red-200"
        >
          <view class="w-[24rpx] h-[24rpx] bg-red-500 rounded-full flex items-center justify-center mr-[8rpx]">
            <IconFont font-class-name="iconfont" class-prefix="icon" name="suo" size="12" color="#ffffff"></IconFont>
          </view>
          <text class="text-[20rpx] text-red-600 font-medium">付费</text>
        </view>
      </view>
    </view>

    <!-- 视频播放器 -->
    <view class="relative bg-black mb-[20rpx]">
      <image v-if="!hasPurchased" :src="useImage(video.cover || '')" class="w-full bg-gray-200 mb-2" mode="widthFix" />
      <video v-else
        :src="useImage(video.vedio || '')"
        :controls="hasPurchased"
        class="w-full !h-420rpx object-contain bg-gray-200"
      />

      <!-- 未购买时的遮罩 -->
      <view
        v-if="!hasPurchased"
        class="absolute inset-0 flex flex-col items-center justify-center bg-black/60"
      >
        <view class="w-[80rpx] h-[80rpx] bg-white bg-opacity-20 rounded-full flex items-center justify-center mb-[16rpx]">
          <IconFont font-class-name="iconfont" class-prefix="icon" name="suo" size="40" color="#ffffff"></IconFont>
        </view>
        <view class="text-white text-[28rpx] font-bold mb-[8rpx]">视频已锁定</view>
        <view class="text-white text-[24rpx] text-opacity-80">购买后观看完整视频</view>
      </view>
    </view>

    <!-- 描述内容 -->
    <view v-if="video.detail" class="relative bg-white p-[32rpx] mb-[20rpx]">
      <!-- 内容容器，限制显示行数 -->
      <view 
        class="text-[28rpx] text-gray-700 leading-[1.8] relative"
        :class="!hasPurchased ? 'max-h-[112rpx] overflow-hidden locked-content' : ''"
      >
        <view v-html="video.detail"></view>
        
        <!-- 未购买时的遮罩层 -->
        <view 
          v-if="!hasPurchased"
          class="absolute inset-0 bg-gradient-to-b from-white via-white to-transparent"
          style="background: linear-gradient(to bottom, rgba(255,255,255,1) 0%, rgba(255,255,255,1) 60%, rgba(255,255,255,0.8) 80%, rgba(255,255,255,0) 100%);"
        ></view>
        
        <!-- 未购买时的锁定图标 -->
        <view 
          v-if="!hasPurchased"
          class="absolute bottom-[-40rpx] right-0 flex items-center"
        >
          <view class="w-[32rpx] h-[32rpx] bg-[#667eea] rounded-full flex items-center justify-center mr-[8rpx]">
            <IconFont font-class-name="iconfont" class-prefix="icon" name="suo" size="16" color="#ffffff"></IconFont>
          </view>
          <text class="text-[24rpx] text-[#667eea]">已锁定</text>
        </view>
      </view>
      
      <!-- 未购买时的提示条 -->
      <view 
        v-if="!hasPurchased"
        class="mt-[60rpx] py-[24rpx] px-[32rpx] bg-gradient-to-r from-blue-50 to-purple-50 rounded-[16rpx] border border-blue-100 flex items-center"
      >
        <view class="flex items-center mr-[16rpx]">
          <view class="w-[40rpx] h-[40rpx] bg-[#667eea] rounded-full flex items-center justify-center">
            <IconFont font-class-name="iconfont" class-prefix="icon" name="suo" size="20" color="#ffffff"></IconFont>
          </view>
        </view>
        <view class="flex-1">
          <text class="text-[28rpx] font-bold text-[#333333] block">解锁完整内容</text>
          <text class="text-[24rpx] text-[#666666] block">购买后可观看全文</text>
        </view>
        <nut-button 
          type="primary" 
          size="small" 
          class="gradient-button"
          @tap="buyVideo"
          :loading="loading"
        >
          立即解锁
        </nut-button>
      </view>
    </view>

    <!-- 底部购买栏 -->
    <view
      v-if="video.price > 0"
      class="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-100 p-[24rpx] flex items-center safe-area-bottom shadow-top z-20"
    >
      <view class="flex flex-1 items-center">
        <view class="flex items-center">
          <view class="w-[40rpx] h-[40rpx] bg-gradient-to-r from-[#667eea] to-[#764ba2] rounded-full flex items-center justify-center mr-[16rpx]">
            <IconFont font-class-name="iconfont" class-prefix="icon" name="suo" size="20" color="#ffffff"></IconFont>
          </view>
          <view>
            <text class="text-[24rpx] text-gray-500 block">解锁价格</text>
            <view class="text-[36rpx] font-bold text-red-500">¥{{ video.price.toFixed(2) }}</view>
          </view>
        </view>
      </view>
      
      <nut-button
        type="primary"
        size="large"
        class="flex-1 ml-[32rpx] gradient-button"
        :loading="loading"
        :disabled="hasPurchased"
        @tap="buyVideo"
      >
        {{ loading ? '处理中...' : hasPurchased ? '已购买' : '立即解锁' }}
      </nut-button>
    </view>
    <!-- 底部间距 -->
    <view class="h-[40rpx]"></view>
  </view>
</template>

<style>
/* 顶部阴影 */
.shadow-top {
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
}

/* 描述段落间距 */
.text-gray-700 p {
  margin-bottom: 32rpx;
}

/* 底部安全适配 */
.safe-area-bottom {
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
}

/* 遮罩层样式 */
.bg-gradient-to-b {
  background: linear-gradient(to bottom, rgba(255,255,255,1) 0%, rgba(255,255,255,1) 60%, rgba(255,255,255,0.8) 80%, rgba(255,255,255,0) 100%);
}

/* 锁定状态样式 */
.locked-content {
  position: relative;
  overflow: hidden;
}

.locked-content::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60rpx;
  background: linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
  pointer-events: none;
}

/* 按钮渐变效果 */
.gradient-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.gradient-button:active {
  transform: translateY(2rpx);
  box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.3);
}
</style>